#!/usr/bin/python

import sys
import datetime
import itertools
import csv

import common

common.setupEnv(globals())

usage = "Import ICICI trade records"

parser = common.StockieOptionParser(usage=usage)
parser.add_posarg('csvfilename', dest="csv_path")
options, args = parser.parse_args()

def prepareRow(row):
    new_row = []
    for item in row:
        if '.' in item and item.replace('.', '').isdigit():
            item = float(item)
        elif item.isdigit():
            item = int(item)
        elif '/' in item:
            dd, mm, yy = [int(t) for t in item.split('/')]
            item = datetime.date(2000 + yy, mm, dd)
        new_row.append(item)
    return new_row

def scriptBy(data):
    script_sorter = lambda row: row[1]
    tr_getter = lambda row: row[2]
    data.sort(key = script_sorter)
    d = dict ()
    for (script_name, rows) in itertools.groupby(data, script_sorter):
        d[script_name] = {}
        rows = sorted(list(rows), key = tr_getter)
        for (tr, grp) in itertools.groupby(rows, tr_getter):
            d[script_name][tr] = list(grp)
    return d

if len(sys.argv) < 2:
    sys.exit("usage: %s <csvfilenames>" % sys.argv[0])

this_yr_start = datetime.date(2007, 4, 1)
this_yr_end = datetime.date(2008, 3, 31)
raw_data = list(csv.reader(file(options.csv_path)))[1:]
data = [prepareRow(row) for row in raw_data]
scripts_d = scriptBy(data)

for (script_name, script_d) in scripts_d.items():
    if interface.addStock(script_name, "", ""):
        print "Added new stock: %s" % script_name
    for tr_type in script_d:
        for tr in script_d[tr_type]:
            if tr_type.lower() == "sell":
                trade_value = tr[5] - tr[6]
            else:
                trade_value = tr[5] + tr[6]
            interface.addTransaction(script_name, tr_type, tr[3], trade_value, tr[0])
            print "Added new %s for %s: %s (%s) on %s" % (tr_type, script_name, tr[3], trade_value, tr[0])
